package com.wyw.learning.thread.atomic;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 演示AtomicInteger的结拜呢用法，对比非原子类的线程安全问题，使用原子类之后，不需要加锁，也可以保证线程安全。
 *
 * @author Mr Wu    yewen.wu.china@gmail.com
 * <p>
 * Update History:
 * Author        Time            Content
 */
public class AtomicIntegerDemo1 implements Runnable {

    private static final AtomicInteger atomicInteger = new AtomicInteger();

    public void incrementAtomic() {
        atomicInteger.getAndIncrement();//原子类加一
//        atomicInteger.getAndDecrement();//原子类减一
//        atomicInteger.getAndAdd(-90);//自定义长度
    }

    private static volatile int basicCount = 0;

    public void incrementBasic() {
        basicCount++;
    }

    //普通变量的安全方式，但是需要保证这个方法不会越来越大
//    public synchronized void incrementBasic() {
//        basicCount++;
//    }


    public static void main(String[] args) throws InterruptedException {
        AtomicIntegerDemo1 r = new AtomicIntegerDemo1();
        Thread t1 = new Thread(r);
        Thread t2 = new Thread(r);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("原子类的结果：" + atomicInteger.get());
        System.out.println("普通变量的结果：" + basicCount);
    }

    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            incrementAtomic();
            incrementBasic();
        }
    }


}
